﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Configuration;
using System.Web.UI;
using System.Data;
using System.Reflection;
using E;
using System.IO;

namespace M
{
    public class Common
    {
        /// <summary>
        /// Tính giá trị biểu thức chuỗi, ví dụ "2*3+(4/2)" trả về kết quả là 8
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static double Evaluate(string expression)
        {
            var loDataTable = new DataTable();
            var loDataColumn = new DataColumn("Eval", typeof(double), expression);
            loDataTable.Columns.Add(loDataColumn);
            loDataTable.Rows.Add(0);
            return (double)(loDataTable.Rows[0]["Eval"]);
        }

        /// <summary>
        /// Cắt bỏ phần đuôi của chuỗi, thay vào đó là "..."
        /// </summary>
        /// <param name="str"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string StringCut(string str, int maxLength)
        {
            if (str.Length <= maxLength) return str;
            return str.Substring(0, maxLength) + "...";
        }

        public static string GetProjectFolder()
        {
            return HttpContext.Current.Server.MapPath("~/");
        }

        public static void SendEmail(string to, string subject, string body)
        {
            MailMessage m = new MailMessage();
            m.To.Add(to);
            m.Subject = subject;
            m.Body = body;
            SendEmail(m);
        }

        public static void SendEmail(MailMessage m)
        {
            try
            {
                m.From = new MailAddress(C.ConfigController.GetValue(E.Config.Email));
                m.IsBodyHtml = true;
                SmtpClient c = new SmtpClient();
                c.UseDefaultCredentials = false;
                c.Credentials = new NetworkCredential(C.ConfigController.GetValue(E.Config.Email), C.ConfigController.GetValue(E.Config.EmailPassword));
                c.EnableSsl = C.ConfigController.GetValue(E.Config.EmailEnableSsl) == "1";
                c.Host = C.ConfigController.GetValue(E.Config.EmailHostServer);
                c.Port = int.Parse(C.ConfigController.GetValue(E.Config.EmailPort));
                c.Send(m);
            }
            catch (Exception)
            {
                
            }
        }

        public static string GetIpAddress()
        {
            string ipaddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (ipaddress == "" || ipaddress == null)
            {
                ipaddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            return ipaddress;
        }

        public static string GetCookie(string name)
        {
            try
            {
                return HttpContext.Current.Request.Cookies[name].Value;
            }
            catch (Exception)
            {
                return "";
            }
        }

        public static void SetCookie(string name, string value, DateTime expDate)
        {
            HttpContext.Current.Response.Cookies[name].Value = value;
            HttpContext.Current.Response.Cookies[name].Expires = expDate;
        }

        public static string GetUserData(string name)
        {
            object session = HttpContext.Current.Session[name];
            if (session != null) return session + "";
            else return GetCookie(name);
        }

        public static void SetUserData(string name, string value)
        {
            HttpContext.Current.Session[name] = value;
            SetCookie(name, value, DateTime.Now.AddDays(30));
        }

        public static void SetUserData(string name, string value, int days)
        {
            HttpContext.Current.Session[name] = value;
            SetCookie(name, value, DateTime.Now.AddDays(days));
        }

        public static string GetLang(string contentVN)
        {
            return C.LanguageController.GetLang(contentVN);
        }
        public static string Translate(string contentVN)
        {
            return C.LanguageController.Translate(contentVN);
        }

        public static string GetRootAddress()
        {
            //return ConfigurationManager.AppSettings["RootAddress"];
            return HttpContext.Current.Request.Url.Scheme + System.Uri.SchemeDelimiter + HttpContext.Current.Request.Url.Host + (HttpContext.Current.Request.Url.Port != 80 ? ":" + HttpContext.Current.Request.Url.Port : "");
        }

        public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
        {
            DataTable dtReturn = new DataTable();

            // column names 
            PropertyInfo[] oProps = null;

            if (varlist == null) return dtReturn;

            foreach (T rec in varlist)
            {
                // Use reflection to get property names, to create table, Only first time, others 
                //will follow 
                if (oProps == null)
                {
                    oProps = ((Type)rec.GetType()).GetProperties();
                    foreach (PropertyInfo pi in oProps)
                    {
                        Type colType = pi.PropertyType;

                        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                        {
                            colType = colType.GetGenericArguments()[0];
                        }

                        dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                    }
                }

                DataRow dr = dtReturn.NewRow();

                foreach (PropertyInfo pi in oProps)
                {
                    dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
                    (rec, null);
                }

                dtReturn.Rows.Add(dr);
            }
            return dtReturn;
        }

        public static void CheckLogin()
        {
            string currentURL = HttpUtility.UrlEncode(HttpContext.Current.Request.Url.AbsoluteUri);
            if (C.TrangController.GetCurrentPage() == "~/User/Login/Login.aspx") return;
            if (!C.UserRoleController.CanAccess(C.UserController.GetUsername(), C.UserController.GetPassword(), C.TrangController.GetCurrentPage()))
                HttpContext.Current.Response.Redirect(M.Common.GetRootAddress() + "/User/Login/Login.aspx?returnURL=" + currentURL);

        }

        public static void CheckWWW()
        {
            string currentUrl = HttpContext.Current.Request.Url.AbsoluteUri;
            if (currentUrl.StartsWith("http://www."))
                HttpContext.Current.Response.RedirectPermanent(currentUrl.Replace("http://www.", "http://"));
        }

        public static string GetPaging(int totalResult, int itemPerPage, ref int currentPageNumber)
        {
            string currentUrl = HttpContext.Current.Request.Url.AbsoluteUri;
            int totalPage = totalResult % itemPerPage == 0 ? totalResult / itemPerPage : totalResult / itemPerPage + 1;
            if (currentPageNumber > totalPage) currentPageNumber = totalPage;
            string ret = File.ReadAllText(HttpContext.Current.Server.MapPath(@"~\File\TemplateHtml\Paging\Outer.htm"));
            ret = ret.Replace("{totalResult}", "" + totalResult);
            ret = ret.Replace("{currentPage}", "" + currentPageNumber);
            ret = ret.Replace("{totalPage}", "" + totalPage);
            string itemTemplate = File.ReadAllText(HttpContext.Current.Server.MapPath(@"~\File\TemplateHtml\Paging\Item.htm"));
            string items = "";

            if (currentPageNumber - 4 > 0)
            {
                items += itemTemplate.Replace("{text}", "First").Replace("{url}", M.Http.SetPara(currentUrl, "page", "1")).Replace("{value}", "1");
            }
            if (currentPageNumber - 1 > 0)
            {
                items += itemTemplate.Replace("{text}", "Prev").Replace("{url}", M.Http.SetPara(currentUrl, "page", "" + (currentPageNumber - 1))).Replace("{value}", "" + (currentPageNumber - 1));
            }
            if (currentPageNumber - 3 > 0)
            {
                items += itemTemplate.Replace("{text}", "" + (currentPageNumber - 3)).Replace("{url}", M.Http.SetPara(currentUrl, "page", "" + (currentPageNumber - 3))).Replace("{value}", "" + (currentPageNumber - 3));
            }
            if (currentPageNumber - 2 > 0)
            {
                items += itemTemplate.Replace("{text}", "" + (currentPageNumber - 2)).Replace("{url}", M.Http.SetPara(currentUrl, "page", "" + (currentPageNumber - 2))).Replace("{value}", "" + (currentPageNumber - 2));
            }
            if (currentPageNumber - 1 > 0)
            {
                items += itemTemplate.Replace("{text}", "" + (currentPageNumber - 1)).Replace("{url}", M.Http.SetPara(currentUrl, "page", "" + (currentPageNumber - 1))).Replace("{value}", "" + (currentPageNumber - 1));
            }
            items += itemTemplate.Replace("{text}", "" + currentPageNumber).Replace("{url}", M.Http.SetPara(currentUrl, "page", "" + currentPageNumber)).Replace("{value}", "" + currentPageNumber).Replace("{class}", "paging-current-page");
            if (currentPageNumber + 1 <= totalPage)
            {
                items += itemTemplate.Replace("{text}", "" + (currentPageNumber + 1)).Replace("{url}", M.Http.SetPara(currentUrl, "page", "" + (currentPageNumber + 1))).Replace("{value}", "" + (currentPageNumber + 1));
            }
            if (currentPageNumber + 2 <= totalPage)
            {
                items += itemTemplate.Replace("{text}", "" + (currentPageNumber + 2)).Replace("{url}", M.Http.SetPara(currentUrl, "page", "" + (currentPageNumber + 2))).Replace("{value}", "" + (currentPageNumber + 2));
            }
            if (currentPageNumber + 3 <= totalPage)
            {
                items += itemTemplate.Replace("{text}", "" + (currentPageNumber + 3)).Replace("{url}", M.Http.SetPara(currentUrl, "page", "" + (currentPageNumber + 3))).Replace("{value}", "" + (currentPageNumber + 3));
            }
            if (currentPageNumber + 1 <= totalPage)
            {
                items += itemTemplate.Replace("{text}", "Next").Replace("{url}", M.Http.SetPara(currentUrl, "page", "" + (currentPageNumber + 1))).Replace("{value}", "" + (currentPageNumber + 1));
            }
            if (currentPageNumber + 4 <= totalPage)
            {
                items += itemTemplate.Replace("{text}", "Last").Replace("{url}", M.Http.SetPara(currentUrl, "page", "" + totalPage)).Replace("{value}", "" + totalPage);
            }

            ret = ret.Replace("{item}", items);
            if (currentPageNumber == 0) currentPageNumber = 1;
            return ret;
        }

        public static void Refresh()
        {
            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri);
        }

        public static void GoToPreviousPage()
        {
            Page page = HttpContext.Current.Handler as Page;
            if (page == null) return;

            if (page.Master is HCFramework.Master.Admin.Admin)
            {
                HCFramework.Master.Admin.Admin master = (HCFramework.Master.Admin.Admin)page.Master;
                if (master.litPreviousPage.Text == "") return;
                page.Response.Redirect(master.litPreviousPage.Text);
            }
            if (page.Master is HCFramework.Master.Normal.Normal)
            {
                HCFramework.Master.Normal.Normal master = (HCFramework.Master.Normal.Normal)page.Master;
                if (master.litPreviousPage.Text == "") return;
                page.Response.Redirect(master.litPreviousPage.Text);
            }
        }

        public static void UpdateSession(string name)
        {
            string cookie = GetCookie(name);
            SetUserData(name, cookie);
        }
    }
}